<template>
  <div class="main ad-manage-edit">
    <el-form class="section" :model="formData" :rules="formRules" size="medium" ref="form" label-width="150px">
      <el-form-item label="分类标题：" prop="title">
        <el-input v-model="formData.title" placeholder="输入标题2-8字"></el-input>
      </el-form-item>
      <el-form-item label="分类副标题：" prop="subtitle">
        <el-input v-model="formData.subtitle" placeholder="输入副标题2-8字"></el-input>
      </el-form-item>
      <el-form-item label="选择商品：" :rules="commonRules.notNullRule">
        <div>
          <label class="input-checkbox" v-if="goodsCategory.length">
            <input type="checkbox" v-model="allSel" @click="allSelClick"/>
            <span>全选</span>
          </label>
          <el-tree
            :data="goodsCategory"
            show-checkbox
            check-on-click-node
            accordion
            node-key="id"
            ref="tree"
            highlight-current
            :props="{ children: 'children', label: 'name'}"
            :default-checked-keys="tempGoodsCategory"
            @check="setGoodsCategory">
          </el-tree>
        </div>
        <div style="margin-top: 10px;">
          <el-button type="primary" icon="el-icon-plus" size="small" @click="chooseGoods" plain>添加商品</el-button>
          <el-button type="success" icon="el-icon-plus" size="small" @click="choosePackage" plain>添加套餐</el-button>
          <el-button type="danger" size="small" @click="batchDel" plain>批量移除</el-button>
        </div>
        <div>
          <div style="margin-top: 10px;">
            <el-table :data="tempGoodsSelect" border highlight-current-row style="width:60%" @select="handleSelect" @select-all="handleSelect">
              <el-table-column align="center" type="selection" width="60"></el-table-column>
              <el-table-column align="center" width="60" label="序号" type="index"></el-table-column>
              <el-table-column align="center" width="300" label="ID" prop="goods_id"></el-table-column>
              <el-table-column align="center" min-width="300" label="名称" prop="title"></el-table-column>
              <el-table-column align="center" label="操作" width="100">
                <template slot-scope="scope">
                  <el-button type="danger" size="mini" @click="removeTempSelect(scope.row)">移除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="icon图标：">
        <el-upload
          class="avatar-uploader"
          accept="image/*"
          :action="upladUrl"
          name="file"
          :show-file-list="false"
          :on-success="iconSuccess"
          :before-upload="beforeUpload">
          <img v-if="formData.icon" :src="formData.icon" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="banner图片：">
        <el-upload
          class="avatar-uploader"
          accept="image/*"
          :action="upladUrl"
          name="file"
          :show-file-list="false"
          :on-success="bannerSuccess"
          :before-upload="beforeUpload">
          <img v-if="formData.banner" :src="formData.banner" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="排序：">
        <el-input v-model="formData.showSort" placeholder="排序" @input="formData.showSort=$event.replace(/[^\d]/g,'')"></el-input>
      </el-form-item>
      <el-form-item label="是否可用：">
        <el-switch
          v-model="formData.enable"
          active-color="#13ce66"
          inactive-color="#ff4949"
          active-text="是"
          inactive-text="否"
          :active-value="1"
          :inactive-value="0">
        </el-switch>
      </el-form-item>
      <el-form-item label="备注：">
        <el-input type="textarea" v-model="formData.note" placeholder="备注" :rows="5" maxlength="1024"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="success" :loading="btnLoading" @click="save">保存</el-button>
        <el-button type="info"  @click="$router.push({name: 'productRecommend'})">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  export default {
    name: 'edit',
    data () {
      return {
        // 默认商品分类
        tempGoodsCategory: [],
        // 商品分类
        goodsCategory: [],
        tempGoodsSelect: [],
        btnLoading: false,
        formData: {
          title: '',
          subtitle: '',
          cateList: [],
          icon: '',
          banner: '',
          showSort: null,
          enable: 0,
          note: ''
        },
        formRules: {
          title: [
            {required: true, message: '不能为空', trigger: 'change'},
            {min: 2, message: '不能小于2个字', trigger: 'change'},
            {max: 8, message: '不能超过8个字', trigger: 'change'}
          ],
          subtitle: [
            {min: 2, message: '不能小于2个字', trigger: 'change'},
            {max: 8, message: '不能超过8个字', trigger: 'change'}
          ]
        },
        ids: [],
        allSel:false
      }
    },
    created () {
      this.fetchCategoryData()
    },
    props: {
      id: { default: '' }
    },
    computed: {
      isEdit() {
        return this.id && this.$route.name === 'productRecommendEdit'
      },
    },
    methods: {
      // 删除商品列表
      removeTempSelect(item) {
        const _this = this
        this.$confirm(`确定要删除 ${item.title} 吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          _this.tempGoodsSelect.splice(_this.tempGoodsSelect.indexOf(item), 1)
        }).catch(err => {
          console.log(err)
        });
      },
      // 选择商品类型
      setGoodsCategory (obj, checkedObj) {
        this.formData.cateList = []
        let idlist = []
        checkedObj.checkedNodes.map(item => {
          idlist.push(item.id)
          this.formData.cateList.push({
            cateId: item.id,
            cateName: item.name,
            cateType: 'cate'
          })
        })
        let flag = true
        this.goodsCategory.forEach(item => {
          if(!idlist.includes(item.id)){
            console.log(item.id)
            flag = false
          }
        })
        this.allSel = flag
      },
      // 获取商品分类
      fetchCategoryData () {
        this.request({
          url: '/bsnl-product/category/tree',
          method: 'get'
        }).then(({data}) => {
          this.goodsCategory = data ? data : []
          if (this.id) this.initDetail()
        }).catch(err => {
          this.goodsCategory = []
          if (this.id) this.initDetail()
        });
      },
      // 添加套餐
      choosePackage () {
        let selected = this.tempGoodsSelect.filter(item=>item.type===2).map(item => {
          return {
            packageId: item.goods_id,
            image: item.pic,
            name: item.title,
            subTitle: item.subtitle,
            marketValue: item.marketValue,
            price: item.price
          }
        });
        this.packageChoose({}, selected).then(val => {
          this.tempGoodsSelect = this.tempGoodsSelect.filter(item=>item.type===1).concat(val.map(item => {
            return {
              goods_id: item.packageId,
              pic: item.image,
              title: item.name,
              subtitle: item.subTitle,
              marketValue: item.marketValue,
              price: item.price,
              type: 2,
              from_type: 2
            }
          }))
        });
      },
      // 添加商品
      chooseGoods () {
        let selected = this.tempGoodsSelect.filter(item=>item.type===1).map(item => {
          return {
            goodsId: item.goods_id,
            image: item.pic,
            name: item.title,
            subName: item.subtitle,
            marketValue: item.marketValue,
            price: item.price
          }
        });
        this.goodsChoose({}, selected).then(val => {
          this.tempGoodsSelect = this.tempGoodsSelect.filter(item=>item.type===2).concat(val.map(item => {
            return {
              goods_id: item.goodsId,
              pic: item.image,
              title: item.name,
              subtitle: item.subName,
              marketValue: item.marketValue,
              price: item.price,
              type: 1,
              from_type: 1
            }
          }))
        })
      },
      //  获取内容
      initDetail () {
        this.request({
          url: `/manage-home-web/cateRecommend/list/${this.id}`,
          method: 'get',
          params: {
            id: this.id
          }
        }).then(({data}) => {
          this.formData = {...data}
          this.formData.cateList = []
          let temp = []
          data.mapCateList.cate && data.mapCateList.cate.map(item => {
            temp.push(item.cateId)
            this.formData.cateList.push({
              cateId: item.cateId,
              cateName: item.cateName,
              cateType: 'cate'
            })
          })
          this.tempGoodsCategory = temp
          data.mapCateList.goods && data.mapCateList.goods.map(item => {
            this.tempGoodsSelect.push({
              goods_id: item.cateId,
              title: item.cateName,
              type: 1,
              cateType: item.cateType
            })
            this.formData.cateList.push({
              cateId: item.cateId,
              cateName: item.cateName,
              cateType: 'goods'
            })
          })
          data.mapCateList.package && data.mapCateList.package.map(item => {
            this.tempGoodsSelect.push({
              goods_id: item.cateId,
              title: item.cateName,
              type: 2,
              cateType: item.cateType
            })
            this.formData.cateList.push({
              cateId: item.cateId,
              cateName: item.cateName,
              cateType: 'package'
            })
          })
          let flag = true
          this.goodsCategory.forEach(item => {
            if(!this.tempGoodsCategory.includes(item.id.toString())){
              flag = false
            }
          })
          this.allSel = flag
        }).catch(err => {
          console.log(err)
        })
      },
      // 上传成功后返回图片地址
      // icon图标
      iconSuccess (res, file) {
        this.formData.icon = this.replaceImgUrl(res.filePath)
      },
      // banner图片
      bannerSuccess (res, file) {
        this.formData.banner = this.replaceImgUrl(res.filePath)
      },
      // 提交内容
      save () {
        this.$refs.form.validate(valid => {
          if (!valid) {
            return false
          }
          this.formData.cateList = this.formData.cateList.filter(item=>item.cateType==='cate').concat(this.tempGoodsSelect.map(item => {
            return {
              cateId: item.goods_id,
              cateName: item.title,
              cateType: item.type === 1 ? 'goods' : 'package'
            }
          }))
          if (this.formData.cateList.length === 0) {
            this.$message.error('请选择商品或套餐')
            return
          }
          this.btnLoading = true
          this.request({
            url: '/manage-home-web/cateRecommend/edit',
            method: 'post',
            data: {...this.formData}
          }).then(() => {
            this.$message.success('保存成功')
            this.$router.push({name: 'productRecommend'})
            this.btnLoading = false
          }).catch(err => {
            console.log(err)
            this.btnLoading = false
          })
        })
      },
      // 批量删除
      batchDel () {
        if (this.ids.length === 0) {
          this.$message.error('请选择分类商品')
          return
        }
        this.$confirm('确认删除选中商品，删除后不展示，请谨慎处理', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let templist = []
          this.tempGoodsSelect.forEach(item => {
            if(this.ids.includes(item.goods_id)) return
            templist.push(item)
          })
          this.ids = []
          this.tempGoodsSelect = templist
        }).catch(err => {
          console.log(err)
        })
      },
      // 表格复选框
      handleSelect (selection) {
        let idlist = []
        selection.map((item) => {
          idlist.push(item.goods_id) 
        })
        this.ids = idlist
      },
      // 全选框点击
      allSelClick () {
        this.allSel = !this.allSel
        if( this.allSel ){
          this.$refs.tree.setCheckedNodes(this.goodsCategory)
          this.formData.cateList = []
          this.goodsCategory.map(item => {
            this.formData.cateList.push({
              cateId: item.id,
              cateName: item.name,
              cateType: 'cate'
            })
            item.children.map(ele => {
              this.formData.cateList.push({
                cateId: ele.id,
                cateName: ele.name,
                cateType: 'cate'
              })
            })
          })
        } else {
          this.$refs.tree.setCheckedNodes([])
          this.formData.cateList = []
        }
      }
    }
  }
</script>